<?php

class MerchantController extends ToolsBaseController
{
	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow', // allow authenticated user to perform below actions
				//'actions'=>array('logout'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				//'actions'=>array('logout'),
				'users'=>array('*'),
			),
		);
	}
	
	public function actionIndex()
	{
		if (!Yii::app()->request->isAjaxRequest) {
			$this->render('index');
			Yii::app()->end();
		}
		
		//handle page=?
		$page_size = Yii::app()->params['pageSize'];
		$current_page = Yii::app()->request->getParam('page', 1);
		$offset = ($current_page - 1) * $page_size;
		$sql_limit = " LIMIT {$offset}, {$page_size} ";
		
		$params = array();
		$sql_where = '';
		
		//q=?
		$q = Yii::app()->request->getPost('q');
		if (!empty($q)) {
			$sql_where .= ' AND m.id=:qq OR m.postcode=:qq OR m.city=:qq
				OR m.name LIKE :qlike OR m.address LIKE :qlike OR m.biz_area LIKE :qlike OR m.phone LIKE :qlike';
			$params[':qq'] = $q;
			$params[':qlike'] = "%{$q}%";
		}
		
		//post admin
		$id_admin = Yii::app()->request->getPost('id_admin');
		if (!empty($id_admin)) {
			$sql_where .= ' AND m.id_admin=:id_admin ';
			$params[':id_admin'] = $id_admin;
		}
		
		//sort=?
		$sort = Yii::app()->request->getPost('sort');
		if ($sort == 'name') {
			$sql_order_by = ' ORDER BY m.name ASC, m.update_timestamp DESC, m.insert_timestamp DESC ';
		} else {
			$sql_order_by = ' ORDER BY m.update_timestamp DESC, m.insert_timestamp DESC ';
		}
		
		$sql_merchants = 'SELECT m.id, m.url_logo, m.name, m.address, m.biz_area, m.postcode, m.city, m.phone, m.category_key, m.status, t.cuisine_type,
				m.id_admin, a.name AS admin_name,
				(SELECT COUNT(s.id) FROM tbl_merchant_special s WHERE s.id_merchant=m.id AND s.trash=0) AS offers,
				(SELECT SUM(interest_rate)/COUNT(id) FROM tbl_sys_merchant_rate sr WHERE sr.id_merchant=m.id) AS rank
			FROM tbl_merchant_account m
			LEFT JOIN tbl_merchant_tags t ON m.id=t.id_merchant
			LEFT JOIN tbl_sys_admin_account a ON m.id_admin=a.id
			WHERE m.latitude IS NOT NULL AND m.longitude IS NOT NULL '
			. $sql_where
			. $sql_order_by
			. $sql_limit;
		$sql_count = 'SELECT COUNT(m.id) AS total FROM tbl_merchant_account m
			WHERE m.latitude IS NOT NULL AND m.longitude IS NOT NULL ' . $sql_where;
		
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_merchants);
		$rows = $command->queryAll(true, $params);
		$command = $connection->createCommand($sql_count);
		$aTotal = $command->queryRow(true, $params);
		$connection->active = false;
		
		//set pager
		$pages = new CPagination($aTotal['total']);
		$pages->setPageSize($page_size);
		if (Yii::app()->request->isAjaxRequest) {
			$this->renderPartial('_list', array('model' => $rows, 'pages' => $pages));
		} else {
			$this->render('index', array('model' => $rows, 'pages' => $pages));
		}
	}
	
	/**
	 * Create or edit an merchant with form page.
	 */
	public function actionForm($id = null) {
		$model = empty($id) ? new MerchantForm() : $this->_loadModel($id = (int)$id);
		$model->setScenario('profile');
		
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'merchant-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		
		// collect user input data
		if (isset($_POST['MerchantForm'])) {
			//assign to admin
			if (empty($id)) {
				$model->id_admin = Yii::app()->user->id;
			}
			
			
			$model->attributes = $_POST['MerchantForm'];
			
			//set the address
			if (!empty($_POST['MerchantForm']['address'])) {
				$locArray = explode(',', $_POST['MerchantForm']['address']);
				if (count($locArray) > 0) {
					$model->address = trim($locArray[0]);
				}
			}
			
			//set unsafe values which are specified by rules method of MerchantForm class
			$model->url_site = $_POST['MerchantForm']['url_site'];
			$model->url_facebook_page = $_POST['MerchantForm']['url_facebook_page'];
			if (!empty($model->address)) {
				$model->latitude = $_POST['MerchantForm']['latitude'];
				$model->longitude = $_POST['MerchantForm']['longitude'];
			}
			$model->currency_code = 'EUR';
			$model->name = trim($_POST['MerchantForm']['name']);
			$model->brief = trim($_POST['MerchantForm']['brief']);
			$model->update_timestamp = new CDbExpression('NOW()');	//update AR
			
			//format phone
			$model->phone = MerchantObject::formatPhoneNumber($model->phone);
			
			//set biz_area string with comma
			if (isset($_POST['MerchantForm']['biz_area'])) {
				$new_biz_area = implode(',', $_POST['MerchantForm']['biz_area']);
				if ($new_biz_area != $model->biz_area) {
					$model->biz_area = $new_biz_area;
					//add new biz area to table tbl_merchant_area_city
					$sql_clear = 'DELETE FROM tbl_merchant_area_city WHERE biz_area=:biz_area AND city_key=:city_key AND country_code=:country_code ';
					$sql_insert = 'INSERT INTO tbl_merchant_area_city (biz_area, city_key, country_code) VALUES (:biz_area, :city_key, :country_code) ';
					$params = array();
					$params[':city_key'] = $model->city;
					$params[':country_code'] = $model->country_code;

					$connection = Yii::app()->db;
					foreach ($_POST['MerchantForm']['biz_area'] as $v) {
						$params[':biz_area'] = $v;
						$command = $connection->createCommand($sql_clear);
						$command->execute($params);
						$command = $connection->createCommand($sql_insert);
						$command->execute($params);
					}
					$connection->active = false;
				}
			}
			
			// validate user input and redirect to the previous page if valid
			if ($model->save()) {
				
				//save open hours
				if (!empty($_POST['business_hours'])) {
					$sql_hours_delete = 'DELETE FROM tbl_merchant_open_hours WHERE id_merchant=:id_merchant';
					$sql_hours_insert = 'INSERT INTO tbl_merchant_open_hours(id_merchant, week_no, open_hour, close_hour) VALUES (:id_merchant, :week_no, :open_hour, :close_hour)';
					$connection = Yii::app()->db;
					$command = $connection->createCommand($sql_hours_delete);
					$command->execute(array('id_merchant'=>$model->id));
					$command = $connection->createCommand($sql_hours_insert);
					$hittedWeek = array();
					foreach ($_POST['business_hours'] as $v) {
						$aTemp = explode(',', $v);
						if (false === array_search($aTemp[0], $hittedWeek)) {
							$params = array(
								':id_merchant' => $model->id,
								':week_no' => $aTemp[0],
								':open_hour' => $aTemp[1],
								':close_hour' => $aTemp[2],
							);
							$command->execute($params);
							$hittedWeek[] = $aTemp[0];
						}
					}
					$connection->active = false;
				}
				
				$message = '{"success":"Save merchant profie '.$model->id.' done!", "id":'.$model->id.'}';
			} else {
				$message = CActiveForm::validate($model);
				//trace error
				Yii::log('Merchant '.$id.' profile saving is failed! ' . json_encode($model->errors),
					CLogger::LEVEL_WARNING, 'system.web.server');
			}
			
			if (Yii::app()->request->isAjaxRequest) {
				echo $message;
				Yii::app()->end();
			} else {
				Yii::app()->user->setFlash('profile', 'Save merchant profie '.$id.' done!');
				$this->refresh();
				//trace error
				Yii::log('Merchant '.$id.' is using the non-ajax submit.',
					CLogger::LEVEL_WARNING, 'system.web.client');
			}
		}
		
		//2. get merchant's open hours
		$sql_hours = 'SELECT week_no, open_hour, close_hour FROM tbl_merchant_open_hours
			WHERE id_merchant=:id_merchant ORDER BY week_no ASC';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_hours);
		$hours = $command->queryAll(true, array('id_merchant'=>$id));
		
		//3. get merchant's tags
		$sql_tags = 'SELECT cuisine_style, cuisine_type, meal_served, payment_options, service_languages, 
			alcohol_license, dining_ambience, car_parking, additional_details
			FROM tbl_merchant_tags WHERE id_merchant=:id_merchant';
		$command = $connection->createCommand($sql_tags);
		$tags = $command->queryRow(true, array('id_merchant'=>$id));
		$connection->active = false;

		$this->render('form', array(
			'model' => $model,
			'tag' => $tags,
			'aHours' => $hours,
		));
	}
	
	
	/**
	 * Insert logo picture with AJAX.
	 * 160 x 160 (but keep aspect ratio)
	 */
	public function actionUploadLogo()
	{
		$id = Yii::app()->request->getQuery('id');
		if (empty($id)) {
			throw new CHttpException(404, 'Please first save this merchant profile, then upload logo!');
		}
		
		//set folder
		$saved_folder = BUtils::GetUploadingFolder($id);
		$url_folder = BUtils::GetUploadingUrl($id);
		
		Yii::import("ext.EAjaxUpload.qqFileUploader");
		$allowedExtensions = array("jpg","jpeg","gif","png");//array("jpg","jpeg","gif","exe","mov" and etc...
		$sizeLimit = 8 * 1024 * 1024;	// maximum file size in bytes
		$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
		$result = $uploader->handleUpload($saved_folder, 'logo_m_' . $id, true);
		unset($uploader);
		
		//resize logo picture to 160 x 160 size:
		Yii::import('ext.iwi.Iwi');
		$picture = new Iwi($saved_folder . $result['filename']);
		$picture->adaptive(160, 160);
		$picture->save($saved_folder . $result['filename']);
		unset($picture);
		
		//delete the original logo picture (not delete, just keep them there)
		
		//insert into menu table
		$sql_menu = 'UPDATE tbl_merchant_account SET url_logo=:url_logo WHERE id=:id';
		$params_menu = array('id'=>$id, 'url_logo'=>$url_folder . $result['filename']);
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_menu);
		$command->execute($params_menu);
		$connection->active = false;
		$result['url_logo'] = BUtils::GetPictureUrl($url_folder . $result['filename']) . '?t=' . time();
		echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
	}
	
	/**
	 * AJAX publish a special.
	 */
	public function actionPublish($id) {
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		$connection = Yii::app()->db;
		$command = $connection->createCommand('UPDATE tbl_merchant_account SET status=1, published_time_admin=NOW() WHERE id=:id');
		$command->execute(array(':id'=>$id));
		
		//update the admin id
		$command = $connection->createCommand('UPDATE tbl_merchant_account SET id_admin=:id_admin WHERE id=:id AND id_admin IS NULL');
		$command->execute(array(':id'=>$id, ':id_admin'=>Yii::app()->user->id));
		$connection->active = false;
	}
	
	public function actionView($id) {
		if (empty($id)) {
			throw new CHttpException(404, 'The parameter "id" is missing!');
		}
		
		$model = $this->_loadModel($id);
		
		$params = array(':id_merchant'=>$id);
		//1. fetch merchant tags
		$sql_merchant = 'SELECT t.cuisine_type, t.cuisine_style, t.meal_served, t.payment_options, t.service_languages, 
			t.alcohol_license, t.dining_ambience, t.car_parking, t.additional_details
			FROM tbl_merchant_tags t
			WHERE t.id_merchant=:id_merchant ';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_merchant);
		$row = $command->queryRow(true, $params);
		
		//2. fetch merchant's open hours
		$sql_hours = 'SELECT week_no, open_hour, close_hour FROM tbl_merchant_open_hours
			WHERE id_merchant=:id_merchant ORDER BY week_no ASC';
		$command = $connection->createCommand($sql_hours);
		$aHours = $command->queryAll(true, $params);
		
		//3. how many offers
		$sql_offers = 'SELECT COUNT(s.id) AS offers FROM tbl_merchant_special s
			WHERE s.id_merchant=:id_merchant AND s.trash=0';
		$command = $connection->createCommand($sql_offers);
		$offers = $command->queryScalar($params);
		
		//4. how many gallery
		$sql_gallery = 'SELECT g.id, g.url_picture, g.title, g.type, g.id_user, UNIX_TIMESTAMP(g.create_time) AS ts_create_time,
			u.username, u.name
			FROM tbl_merchant_gallery g
			LEFT JOIN tbl_user_account u ON u.id=g.id_user
			WHERE id_merchant=:id_merchant
			ORDER BY create_time DESC';
		$command = $connection->createCommand($sql_gallery);
		$gallery_rows = $command->queryAll(true, $params);
		
		//5. how many rates
		$sql_merchant_rates = 'SELECT sr.id, sr.interest_rate, sr.comments, sr.id_admin, sr.update_time, a.name AS admin_name
			FROM tbl_sys_merchant_rate sr
			INNER JOIN tbl_sys_admin_account a ON a.id=sr.id_admin
			WHERE sr.id_merchant=:id_merchant
			ORDER BY sr.create_time DESC';
		$command = $connection->createCommand($sql_merchant_rates);
		$rate_rows = $command->queryAll(true, $params);
		$connection->active = false;
		
		//find the current admin's comment
		$rate_row = array();
		foreach ($rate_rows as $rate) {
			if ($rate['id_admin'] == Yii::app()->user->id) {
				$rate_row = $rate; break;
			}
		}
		
		$this->render('view', array(
			'model' => $model,
			'model_rate' => (empty($rate_row['id'])) ? new SysMerchantRateForm() : $this->_loadMerchantRateModel($rate_row['id']),
			'tag' => $row,
			'aHours' => $aHours,
			'offers' => $offers,
			'gallery_rows' => $gallery_rows,
			'rate_rows' => $rate_rows,
		));
	}
	
	/**
	 * Feature page 
	 */
	public function actionFeature($id)
	{
		$model = $this->_loadModel($id);
		$model->setScenario('profile');
		
		//2. fetch merchant tags
		$sql_tags = 'SELECT cuisine_style, cuisine_type, meal_served, payment_options, service_languages, 
			alcohol_license, dining_ambience, car_parking, additional_details
			FROM tbl_merchant_tags WHERE id_merchant=:id_merchant';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_tags);
		$tags = $command->queryRow(true, array(':id_merchant'=>$id));
		
		//3. fetch merchant's open hours
		$sql_hours = 'SELECT week_no, open_hour, close_hour FROM tbl_merchant_open_hours
			WHERE id_merchant=:id_merchant ORDER BY week_no ASC';
		$command = $connection->createCommand($sql_hours);
		$hours = $command->queryAll(true, array(':id_merchant'=>$id));
		$connection->active = false;

		if ($model->category_key == 'restaurants') {
			$page = 'feature_restaurants';
		} else $page = 'feature';
		$this->render($page, array(
			'model' => $model,
			'tag' => $tags,
			'aHours' => $hours
		));
	}
	
	/**
	 * Save tags with AJAX.
	 */
	public function actionSaveTags($id)
	{
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		//get post data
		$sql_insert = 'INSERT INTO tbl_merchant_tags(';
		$sql_insert_value = ' VALUES(';
		$params = array();
		foreach ($_POST as $key => $value) {
			if (!empty($value)) {
				if (is_array($value)) {
					$params[$key] = implode(',', $_POST[$key]);
					$sql_insert .= "{$key}, ";
					$sql_insert_value .= ":{$key}, ";
				} elseif ($key === 'alcohol_license') {
					$params[$key] = $_POST[$key];
					$sql_insert .= "{$key}, ";
					$sql_insert_value .= ":{$key}, ";
				}
			}
		}
		$sql_insert .= 'id_merchant)';
		$sql_insert_value .= ":id_merchant)";
		$params['id_merchant'] = $id;
		
		$sql_delete = 'DELETE FROM tbl_merchant_tags WHERE id_merchant=:id_merchant';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_delete);
		$command->execute(array(':id_merchant'=>$id));
		$command = $connection->createCommand($sql_insert . $sql_insert_value);
		$command->execute($params);
		$connection->active = false;
		
		echo '{"success":"'.BUtils::T('detail_features_save_done_msg').'"}';
	}
	
	/**
	 * Gets neighborhoods.
	 */
	public function actionGetNeighborhoods()
	{
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		$city_key = Yii::app()->request->getParam('city_key');
		if (empty($city_key)) {
			$sql_areas = 'SELECT biz_area AS value FROM tbl_sys_area_city WHERE city_key IN (:city1, :city2, :city3) ORDER BY biz_area ';
			$params = array(':city1' => 'helsinki', ':city2' => 'espoo', ':city3' => 'vantaa');
		} else {
			$city_key = strtolower($city_key);
			$sql_areas = 'SELECT biz_area AS value FROM tbl_sys_area_city WHERE city_key=:city_key ORDER BY biz_area ';
			$params = array(':city_key' => $city_key);
		}
		//fetch cities form merchant accounts
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_areas);
		$rows = $command->queryAll(true, $params);
		$connection->active = false;
		
		$this->renderPartial('_biz_area', array(
			'rows' => $rows,
		));
	}
	
	/**
	 * Insert menu picture with AJAX 
	 */
	public function actionUploadGallery($id)
	{
		if (empty($id)) {
			throw new CHttpException(404, 'The parameter "id" is missing!');
		}
		
		//set folder
		$saved_folder = BUtils::GetUploadingFolder($id);
		$url_folder = BUtils::GetUploadingUrl($id);
		
		Yii::import("ext.EAjaxUpload.qqFileUploader");
		$prefix = Yii::app()->request->getParam('prefix', null);
		$allowedExtensions = array("jpg","jpeg","gif","png");
		$sizeLimit = 8 * 1024 * 1024;
		$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
		$result = $uploader->handleUpload($saved_folder, uniqid($prefix));
		unset($uploader);
		
		//thumb picture
		$thumb = 'thumb_' . $result['filename'];
		//thumb picture 2
		$thumb_200h = 'thumb_200h_' . $result['filename'];
		
		try {
			//resize picture to 640 x 640.
			Yii::import('ext.iwi.Iwi');
			$picture = new Iwi($saved_folder . $result['filename']);
			$minSize = $picture->getMinSize();
			if ($minSize > 640) $minSize = 640;
			$width = $minSize;
			$height = $picture->getRatio() * $width;
			$picture->adaptive($minSize, $height);
			$picture->save($saved_folder . $result['filename']);
			// 120x120
			$picture->adaptive(120, 120);
			$picture->save($saved_folder . $thumb);
			// 283x200
			$picture->adaptive(283, 200);
			$picture->save($saved_folder . $thumb_200h);
			unset($picture);
		} catch (Exception $ex) {
			echo '{"error" : "Photo cannot be saved!"}';
			Yii::app()->end();
		}
		
		//delete the original picture (not delete, just keep them there)
		
		//insert into menu table
		$connection = Yii::app()->db;
		$sql_photo = 'INSERT INTO tbl_merchant_gallery (id_merchant, url_picture, type) VALUES (:id_merchant, :url_picture, 0)';
		$command = $connection->createCommand($sql_photo);
		$command->execute(array('id_merchant'=>$id, 'url_picture'=>$url_folder . $thumb));
		
		$command = $connection->createCommand('select id FROM tbl_merchant_gallery WHERE url_picture=:url_picture');
		$row = $command->queryRow(true, array('url_picture'=>$url_folder . $thumb));
		$connection->active = false;
		
		//add id
		if (empty($row['id'])) {
			echo '{"error" : "Photo cannot be saved!"}';
		} else {
			$result['id'] = $row['id'];
			$result['url_thumb'] = $url_folder . $thumb;
			$result['url_picture'] = $url_folder . $result['filename'];
			$result['time'] = Yii::app()->locale->dateFormatter->formatDateTime(time());
			echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
		}
	}
	
	/**
	 * Delete photo of gallery.
	 * @param int $id the id of tbl_merchant_gallery.
	 * @param int $mid the id_merchant of tbl_merchant_gallery.
	 * @throws CHttpException
	 */
	public function actionDeleteGallery($id, $mid) {
		if (empty($id)) {
			throw new CHttpException(404, 'The parameter id is missing!');
		}
		if (empty($mid)) {
			throw new CHttpException(404, 'The parameter mid is missing!');
		}
		
		$sql_delete = 'DELETE FROM tbl_merchant_gallery WHERE id_merchant=:id_merchant AND id=:id';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_delete);
		$command->execute(array('id_merchant'=>$mid, 'id'=>$id));
		$connection->active = false;

		//delete picture file
		$url_picture = Yii::app()->request->getParam('url');
		if (!empty($url_picture)) {
			//find file name
			$tmp = explode('/', $url_picture);
			$thumbName = array_pop($tmp);
			$uploadPath = $saved_folder = BUtils::GetUploadingFolder($mid);
			@unlink($uploadPath . $thumbName);
			$thumbName200 = str_replace('thumb_', 'thumb_200h_', $thumbName);
			@unlink($uploadPath . $thumbName200);
			$fileName = str_replace('thumb_', '', $thumbName);
			@unlink($uploadPath . $fileName);
		}
	}
	
	/**
	 * Save admin's merchant comments with rates.
	 */
	public function actionSaveRate()
	{
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		$id = Yii::app()->request->getParam('id');
		$id_merchant = Yii::app()->request->getParam('mid');
		if (empty($id_merchant)) {
			throw new CHttpException(404, 'The parameter "mid" is missing!');
		}
		
		$model = (empty($id)) ? new SysMerchantRateForm() : $this->_loadMerchantRateModel($id);
		$model->attributes = $_POST['SysMerchantRateForm'];
		$model->id_admin = Yii::app()->user->id;
		$model->id_merchant = $id_merchant;
		$model->update_time = new CDbExpression('NOW()');
		if ($model->save()) {
			$ret = array(
				'success' => 'Saved comments successfully!',
				'id' => $model->id,
				'html' => '<div id="dlg-rate-'.$model->id.'"><div>'.Yii::app()->user->name.' : '.$model->interest_rate.'</div><div>'.$model->comments.'</div></div>'
			);
			$message = json_encode($ret);
		} else {
			$message = json_encode($model->errors);
			Yii::log('Merchant '.$id.' profile saving is failed! ' . json_encode($model->errors), CLogger::LEVEL_ERROR, 'system.web.server');
		}
		
		echo $message;
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	protected function _loadModel($id) {
		$model = MerchantForm::model()->findByPk($id);
		if ($model===null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}
	
	/**
	 * The model from SysMerchantRateForm
	 */
	protected function _loadMerchantRateModel($id) {
		$model = SysMerchantRateForm::model()->findByPk($id);
		if ($model===null)
			throw new CHttpException(404, 'The requested Rate does not exist.');
		return $model;
	}
}